<template>
  <div>
    <Content title="部门" :subTitle="isNew?'新建':'编辑'" path="/department" v-loading="loading">
      <div slot="body">
        <div style="padding-left: 20px">
          <p style="font-size: 20px">部门</p>
          <el-form :model="form" label-position="left" :rules="rules" ref="form" label-width="140px"
                   class="department-form">
            <el-form-item label="名称" prop="name" class="my-form-item">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="leader" class="my-form-item">
              <el-input v-model="form.leader"></el-input>
            </el-form-item>
            <el-form-item label="上级部门" prop="parent" class="my-form-item" style="width:100%">
              <el-cascader :options="departments" ref="departmentCascader"
                           change-on-select clearable
                           :props="defaultProps" v-model="form.parents" @change="departmentChange"></el-cascader>
            </el-form-item>
            <el-form-item label="优先级" prop="priority" class="my-form-item">
              <el-input v-model="form.priority" type="number"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description" class="my-form-item">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
            <el-form-item label="部门联系电话" prop="tel" class="my-form-item">
              <el-input v-model="form.tel"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Content>
    <div style="padding: 15px">
      <router-link to="/department">
        <el-button plain round type="info" icon="el-icon-back">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="submitForm('form')" icon="el-icon-circle-check">保存</el-button>
    </div>
  </div>
</template>

<script>
  import util from '../../utils/util'
  import {Department} from '../../utils/resource'
  import Content from '../../components/Content.vue'
  import {mapState, mapActions} from 'vuex'
  import {showSaveResponse, validFieldExists, validateForm} from '../../utils/element-helper'
  import department from "../../vuex/modules/department";

  export default {
    name: 'departmentDetail',
    components: {
      Content,
    },
    data() {
      return {
        loading: false,
        isNew: true, // new true or  edit false
        initForm: {},// for edit
        defaultProps: {
          value: "id",
          label: 'name',
          children: 'children',
        },
        form: {
          parents: [],
          parent: 0,
          ancestors: "",
        },
        rules: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
        },
      }
    },
    created() {
      this.loading = true
      let id = this.$route.params.id
      this.isNew = (id == 'new')
      this.setParent()
      if (!this.isNew) {
        //编辑
        this.loadDepartment()
      } else {
        //新建
        this.departmentChange()
      }
      this.disableSelfDepartment()
      this.$nextTick(() => {
        this.loading = false
      })
    },
    computed: {
      ...mapState("department", [
        "departments",
      ]),
    },
    methods: {
      async loadDepartment() {
        let res = await Department.get(this.$route.params.id)
        this.form = res.data
        this.initForm = res.data
        this.form.parents = util.getTreePath(this.departments, Number(res.data.parent))
      },
      disableSelfDepartment() {
        if (!this.isNew) {
          util.disableTreeNode(this.departments, this.$route.params.id)
        }
      },
      departmentChange(data) {
        this.form.ancestors = [].concat(this.form.parents).concat(this.form.id).join(",")
        this.form.parent = this.form.parents[this.form.parents.length - 1]
      },
      setParent() {
        let parent = this.$route.params.parent
        if (!util.isNull(parent)) {
          this.form.parents = util.getTreePath(this.departments, Number(parent))
        }
      },
      submitForm(formName) {
        return validateForm(this, formName, () => {
          showSaveResponse(this, () => Department.save(this.form, this.isNew ? 'post' : 'put'), (res) => this.$router.back())
        })
      },
      validateExists(rule, value, callback) {
        validFieldExists(rule, value, callback, this.initForm[rule.field] != value || this.isNew, (rule, value) => Department.exists(rule, value))
      },
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .department-form {
    width: 90%;
  }

  .my-form-item {
    max-width: 700px;
  }

</style>
<style>
  .my-form-input {
    max-width: 330px;
  }

</style>
